package com.tools.sqlmaker.make.single;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;

import java.util.*;

import static com.tools.sqlmaker.constant.SqlConstant.*;
import static com.tools.sqlmaker.constant.SqlConstant.LEFT_PARENTHESIS;

/**
 * @author: zhoubin
 * @date: 2023/9/26
 */
public class OracleSingleMaker implements SingleMaker {
    @Override
    public String makeSingleSql(Map<String, Object> map, String table) {
        StringBuilder fieldStr = new StringBuilder();
        StringBuilder valStr = new StringBuilder();

        boolean isFirst = true;
        Set<Map.Entry<String, Object>> entries = map.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            String key = entry.getKey().toUpperCase(Locale.ROOT);
            Object value = entry.getValue();

            if (Objects.isNull(value)) {
                continue;
            }

            if (isFirst) {
                isFirst = false;
            } else {
                fieldStr.append(COMMA);
                valStr.append(COMMA);
            }

            fieldStr.append(key);
            if (value instanceof Integer) {
                valStr.append(value);
            } else if (value instanceof Date) {
                String dateStr = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN) + "000";
                valStr.append("TO_TIMESTAMP('").append(dateStr).append("', 'SYYYY-MM-DD HH24:MI:SS:FF6')");
            } else {
                valStr.append(SINGLE_QUOT_MARK).append(value).append(SINGLE_QUOT_MARK);
            }
        }

        StringBuilder sb = new StringBuilder(INSERT_INTO);
        sb.append(table.toUpperCase(Locale.ROOT)).append(RIGHT_PARENTHESIS);
        sb.append(fieldStr).append(VALUES).append(valStr).append(LEFT_PARENTHESIS);

        return sb.toString();
    }
}
